using B.S.BaseData.Api.Read.Command.Hosp;
using B.S.BaseData.Api.Read.Command.HospitalCommand;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interface;
using B.S.BataBase.Domain.AI;
using B.S.BataBase.Domain.DTO;
using B.S.BataBase.Domain.Hosp;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.S.BaseData.Api.Read.CommandHandler.Hosp
{
    public class HospitalShowCommandHandler : IRequestHandler<HospitalShowCommand, APIResult<ApiPaging<Hospital>>>
    {
        private readonly IBaseRepository<Hospital> _repository;

        public HospitalShowCommandHandler(IBaseRepository<Hospital> repository)
        {
            _repository = repository;
        }

        public async Task<APIResult<ApiPaging<Hospital>>> Handle(HospitalShowCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<ApiPaging<Hospital>>();

            try
            {
                var res = _repository.GetAll().Where(x => !x.IsDeleted);

                // 医院名称搜索
                if (!string.IsNullOrEmpty(request.HospitalName))
                {
                    res = res.Where(x => x.HospitalName.Contains(request.HospitalName));
                }

                // 省筛选
                if (!string.IsNullOrEmpty(request.HospitalProvince))
                {
                    res = res.Where(x => x.HospitalProvince.Contains(request.HospitalProvince));
                }

                // 市筛选
                if (!string.IsNullOrEmpty(request.HospitalCity))
                {
                    res = res.Where(x => x.HospitalCity.Contains(request.HospitalCity));
                }
                var totaCount = res.Count();
                var pageCount = (int)Math.Ceiling(totaCount * 1.0 / request.pageSize);
                ApiPaging<Hospital> paging = new ApiPaging<Hospital>();
                paging.TotalPage = pageCount;
                paging.Total = totaCount;
                paging.PageData = res.Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
                result.Data = paging;
                result.Code = ApiEnum.Success;
                result.Msg = "医院查询成功";
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Fail;
                result.Msg = $"查询医院失败：{ex.Message}";
            }

            return result;
        }
    }
} 